import { filter, includes, isArray } from "lodash";
import { useEffect, useMemo, useState } from "react";
import Group from "@/services/group";
import OrgUnit from "@/services/orgunit";
import Enums from "@/services/enums";

export default function useUserGroups(user) {
  const [allGroups, setAllGroups] = useState([]);
  const [isLoadingGroups, setIsLoadingGroups] = useState(true);
  const groups = useMemo(() => filter(allGroups, group => includes(user.groupIds, group.id)), [allGroups, user]);
  const [orgunits, setOrgunits] = useState([]);
  const [isLoadingOrgunits, setIsLoadingOrgunits] = useState(true);
  const [menustyle_enums, setMenustyle_enums] = useState([]);
  const [isLoadingMenustyle, setIsLoadingMenustyle] = useState(true);

  useEffect(() => {
    let isCancelled = false;

    Group.query().then(groups => {
      if (!isCancelled) {
        setAllGroups(isArray(groups) ? groups : []);
        setIsLoadingGroups(false);
      }
    });
    OrgUnit.queryActive().then(results => {
      if (!isCancelled) {
        setOrgunits(results.map(({ id, code, name }) => ({ value: id, name: name })));
        setIsLoadingOrgunits(false);
      }
    });

    Enums.items('menustyle_enum').then(data => {
      if (!isCancelled) {
        setMenustyle_enums(data.map(({ value, label }) => ({ value: value, name: label })));
        setIsLoadingMenustyle(false);
      }
    });
  }, []);

  return useMemo(() => ({ groups, allGroups, isLoadingGroups, orgunits, isLoadingOrgunits, menustyle_enums, isLoadingMenustyle }), [groups, allGroups, isLoadingGroups, orgunits, isLoadingOrgunits, menustyle_enums, isLoadingMenustyle]);
}
